#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# Copyright Authors of Cilium

#
# Execute command in the network namespace of the named k8s POD
# E.g.:
#
# $ nsexec hello ip addr
# $ nsexec hello -- ip addr
#
# Both would show the IP interfaces in the network namespace of a
# local k8s docker container named "k8s_POD_hello*", given that there
# is only one docker container that starts with that name.  "ip" is
# run from your current environment, it does not need to exist within
# the k8s POD.
#
# This has the limitation that this only works if k8s containers are
# run via Docker.
#

set -e

CONTAINER_ID=$(docker ps -q --filter "name=k8s_POD_$1")
if [ "$(echo ${CONTAINER_ID} | wc -w)" -ne "1" ] ; then
    echo "Argument must be a unique prefix of the name of a single running k8s POD. Current docker containers matching \"$1\" are:"
    docker ps --filter "name=k8s_POD_$1"
    exit 1
fi

PID=$(docker inspect -f '{{.State.Pid}}' ${CONTAINER_ID})
[ -z "${PID}" ] && exit 1

[ ! -d "/var/run/netns" ] && sudo mkdir -p /var/run/netns

function cleanup {
    sudo rm /var/run/netns/${CONTAINER_ID}
}

# Create and remove netns link only if needed
if [ ! -L /var/run/netns/${CONTAINER_ID} ] ; then
    sudo ln -sfT /proc/${PID}/ns/net /var/run/netns/${CONTAINER_ID}
    trap cleanup EXIT
fi

shift
[ "$1" = "--" ] && shift
sudo ip netns exec ${CONTAINER_ID} $@
